package com.eshop.utils;

import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.slf4j.Logger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContextAware;

public class SpringContextHolder implements ApplicationContextAware, DisposableBean
{
    private static final Logger log;
    private static ApplicationContext applicationContext;
    
    public static <T> T getBean(final String name) {
        assertContextInjected();
        return (T)SpringContextHolder.applicationContext.getBean(name);
    }
    
    public static <T> T getBean(final Class<T> requiredType) {
        assertContextInjected();
        return (T)SpringContextHolder.applicationContext.getBean((Class)requiredType);
    }
    
    private static void assertContextInjected() {
        if (SpringContextHolder.applicationContext == null) {
            throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
        }
    }
    
    private static void clearHolder() {
        SpringContextHolder.log.debug("清除SpringContextHolder中的ApplicationContext:" + SpringContextHolder.applicationContext);
        SpringContextHolder.applicationContext = null;
    }
    
    public void destroy() {
        clearHolder();
    }
    
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        if (SpringContextHolder.applicationContext != null) {
            SpringContextHolder.log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
        }
        SpringContextHolder.applicationContext = applicationContext;
    }
    
    static {
        log = LoggerFactory.getLogger((Class)SpringContextHolder.class);
        SpringContextHolder.applicationContext = null;
    }
}
